// 用户信息处理脚本
(function() {
    'use strict';
    
    console.log('user-info.js loaded');
    
    // 确保DOM完全加载后执行
    function initUserInfo() {
        console.log('Initializing user info...');
        
        // 检查是否已经有顶部导航栏结构
        let userAvatar = document.getElementById('userAvatar');
        let dropdownMenu = document.getElementById('dropdownMenu');
        let welcomeMessage = document.getElementById('welcomeMessage');
        let logoutBtn = document.getElementById('logoutBtn');
        
        // 如果没有顶部导航栏结构，动态创建
        if (!userAvatar) {
            console.log('Creating top header...');
            createTopHeader();
            // 重新获取元素引用
            userAvatar = document.getElementById('userAvatar');
            dropdownMenu = document.getElementById('dropdownMenu');
            welcomeMessage = document.getElementById('welcomeMessage');
            logoutBtn = document.getElementById('logoutBtn');
        }
        
        // 加载用户信息
        loadUserInfo();
        
        // 绑定头像点击事件，显示/隐藏下拉菜单
        if (userAvatar && dropdownMenu) {
            console.log('Binding avatar click events...');
            // 先移除可能存在的事件监听，避免重复绑定
            const newAvatar = userAvatar.cloneNode(true);
            userAvatar.parentNode.replaceChild(newAvatar, userAvatar);
            userAvatar = newAvatar;
            
            userAvatar.addEventListener('click', function() {
                dropdownMenu.classList.toggle('show');
            });
            
            // 点击页面其他地方关闭下拉菜单
            document.addEventListener('click', function(event) {
                if (!userAvatar.contains(event.target) && !dropdownMenu.contains(event.target)) {
                    dropdownMenu.classList.remove('show');
                }
            });
        }
        
        // 绑定退出登录事件
        if (logoutBtn) {
            console.log('Binding logout button event...');
            // 先移除可能存在的事件监听，避免重复绑定
            const newLogoutBtn = logoutBtn.cloneNode(true);
            logoutBtn.parentNode.replaceChild(newLogoutBtn, logoutBtn);
            logoutBtn = newLogoutBtn;
            
            logoutBtn.addEventListener('click', function(e) {
                e.preventDefault();
                logout();
            });
        }
    }
    
    // 动态创建顶部导航栏
    function createTopHeader() {
        // 检查是否已经有main-content容器
        let mainContent = document.querySelector('.main-content');
        
        if (!mainContent) {
            // 如果没有，创建一个
            mainContent = document.createElement('div');
            mainContent.className = 'main-content';
            
            // 保存现有内容
            const existingContent = document.body.innerHTML;
            document.body.innerHTML = '';
            
            // 确保导航栏容器在最前面
            const navbarContainer = document.getElementById('navbar-container');
            if (navbarContainer) {
                document.body.appendChild(navbarContainer);
            }
            
            // 添加main-content
            document.body.appendChild(mainContent);
            mainContent.innerHTML = existingContent;
        }
        
        // 检查是否已经有header
        if (!document.querySelector('.header')) {
            // 创建顶部header
            const header = document.createElement('div');
            header.className = 'header';
            header.innerHTML = `
                <h2>铁路管理系统后台</h2>
                <div class="user-info">
                    <div class="user-dropdown">
                        <div class="user-avatar" id="userAvatar">
                            <img src="https://ui-avatars.com/api/?name=管理员&background=random" alt="用户头像">
                            <span id="welcomeMessage">欢迎您：管理员</span>
                            <i class="fas fa-chevron-down"></i>
                        </div>
                        <div class="dropdown-menu" id="dropdownMenu">
                            <a href="#" id="logoutBtn"><i class="fas fa-sign-out-alt"></i> 退出登录</a>
                        </div>
                    </div>
                </div>
            `;
            
            // 将header插入到main-content的最前面
            if (mainContent.firstChild) {
                mainContent.insertBefore(header, mainContent.firstChild);
            } else {
                mainContent.appendChild(header);
            }
        }
        
        // 确保Font Awesome已加载
        if (!document.querySelector('link[href*="font-awesome"]')) {
            const link = document.createElement('link');
            link.rel = 'stylesheet';
            link.href = 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css';
            document.head.appendChild(link);
        }
    }
    
    // 加载用户信息
    function loadUserInfo() {
        try {
            console.log('Loading user information...');
            // 从localStorage获取用户信息
            const userInfoStr = localStorage.getItem('userInfo');
            const savedAdminName = localStorage.getItem('savedAdminName');
            
            const welcomeMessage = document.getElementById('welcomeMessage');
            const userAvatarImg = document.querySelector('#userAvatar img');
            
            console.log('User info from localStorage:', userInfoStr);
            console.log('Saved admin name:', savedAdminName);
            
            if (userInfoStr) {
                const userInfo = JSON.parse(userInfoStr);
                if (userInfo.username && welcomeMessage) {
                    welcomeMessage.textContent = `欢迎您：${userInfo.username}`;
                    // 更新头像显示用户名称首字母
                    if (userAvatarImg) {
                        userAvatarImg.src = `https://ui-avatars.com/api/?name=${userInfo.username}&background=random`;
                    }
                }
            } else if (savedAdminName && welcomeMessage) {
                // 兼容仅保存了用户名的情况
                welcomeMessage.textContent = `欢迎您：${savedAdminName}`;
                if (userAvatarImg) {
                    userAvatarImg.src = `https://ui-avatars.com/api/?name=${savedAdminName}&background=random`;
                }
            }
        } catch (error) {
            console.error('加载用户信息失败:', error);
        }
    }
    
    // 退出登录函数
    function logout() {
        if (confirm('确定要退出登录吗？')) {
            // 清除localStorage中的用户信息
            localStorage.removeItem('userInfo');
            localStorage.removeItem('savedAdminName');
            localStorage.removeItem('saToken');
            
            // 跳转到登录页面
            window.location.href = '/admin/login.html';
        }
    }
    
    // 当DOM内容加载完成后执行初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 使用setTimeout确保其他脚本已加载
        setTimeout(initUserInfo, 100);
    });
    
    // 导出函数供其他地方使用
    window.initUserInfo = initUserInfo;
    window.loadUserInfo = loadUserInfo;
    window.logout = logout;
})();